package work.jame.blog.framework.utils.http;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson2.JSON;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import work.jame.blog.framework.constant.HttpHeaderConstant;
import work.jame.blog.framework.result.Result;
import work.jame.blog.framework.result.ServerStatusCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author : Jame
 * @date : 2023-05-10 14:33
 **/
public class WebUtils {


    /**
     * 响应result
     *
     * @param response response对象
     * @param result   需要返回的result对象
     */
    public static void respondResult(HttpServletResponse response, Result<?> result) {
        response.setStatus(ServerStatusCode.SUCCESS);
        response.setContentType(HttpHeaderConstant.CONTENT_TYPE_APPLICATION_JSON);
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().print(JSON.toJSONString(result));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取当前请求
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(requestAttributes)) {
            throw new RuntimeException("requestAttributes获取为null");
        }
        return requestAttributes.getRequest();
    }


    /**
     * 获取当前响应
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.isNull(requestAttributes)) {
            throw new RuntimeException("requestAttributes获取为null");
        }
        return requestAttributes.getResponse();
    }


    public static UserAgent getRequestUserAgent(HttpServletRequest request) {
        String userAgent = request.getHeader(HttpHeaderConstant.USER_AGENT);
        if(StringUtils.hasText(userAgent)){
            return UserAgentUtil.parse(userAgent);
        }
        return null;
    }
}
